import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from pathlib import Path
from typing import Dict, Any, List, Optional
from .base_sender import BaseReportSender

class EmailSender(BaseReportSender):
    """邮件发送器"""
    
    def __init__(self, config: Dict[str, Any]):
        """初始化邮件发送器
        
        Args:
            config: 邮件配置信息，包含以下字段：
                - smtp_server: SMTP服务器地址
                - smtp_port: SMTP服务器端口
                - username: 发件人邮箱
                - password: 邮箱密码或授权码
                - from_addr: 发件人地址
                - to_addrs: 收件人地址列表
        """
        super().__init__(config)
        self.required_keys = ['smtp_server', 'smtp_port', 'username', 'password', 'from_addr', 'to_addrs']
        
    def send_report(self, report_path: Path, title: str, content: Optional[str] = None) -> bool:
        """发送测试报告邮件
        
        Args:
            report_path: 报告文件路径
            title: 邮件标题
            content: 邮件内容（可选）
            
        Returns:
            是否发送成功
        """
        if not self._validate_config(self.required_keys):
            return False
            
        try:
            # 创建邮件对象
            msg = MIMEMultipart()
            msg['From'] = self.config['from_addr']
            msg['To'] = ', '.join(self.config['to_addrs'])
            msg['Subject'] = title
            
            # 添加邮件内容
            if content:
                msg.attach(MIMEText(content, 'html'))
                
            # 添加报告附件
            with open(report_path, 'rb') as f:
                attachment = MIMEApplication(f.read())
                attachment.add_header('Content-Disposition', 'attachment', 
                                   filename=report_path.name)
                msg.attach(attachment)
                
            # 发送邮件
            with smtplib.SMTP(self.config['smtp_server'], self.config['smtp_port']) as server:
                server.starttls()
                server.login(self.config['username'], self.config['password'])
                server.send_message(msg)
                
            self.logger.info(f"Successfully sent test report to {', '.join(self.config['to_addrs'])}")
            return True
            
        except Exception as e:
            self.logger.error(f"Failed to send test report: {str(e)}")
            return False 